package com.ym.pms.security.provider;

import com.ym.pms.security.entity.SysUserDetails;
import com.ym.pms.security.service.SysUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @Author: xybh
 * @Description:
 * @Date: Created in 11:29 2020/12/22
 * @Modified:
 */
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private SysUserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String  username = (String)authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        SysUserDetails sysUserDetails = (SysUserDetails) userDetailsService.loadUserByUsername(username);
        if(sysUserDetails == null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        if(!new BCryptPasswordEncoder().matches(password, sysUserDetails.getUPassword())){
            throw new BadCredentialsException("用户名或密码错误");
        }
        if("2".equals(sysUserDetails.getUStatus())){
            throw new LockedException("用户已禁用");
        }

        return new UsernamePasswordAuthenticationToken(sysUserDetails,password ,sysUserDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
